package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.sendRoyaltyManager.OrderSendRoyalty;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.cluePoolManager.ImportFollowVO;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.returnMoney.ReturnMoneyVO;
import com.crm.model.vo.returnMoney.ImportReturnMoneyVO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.ReturnMoneyDbservice;
import com.crm.service.sendRoyaltyManager.SendRoyaltyDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:chaifuyou
 * @Date: 2021/6/15 13:45
 */
public class InsertReturnMoneyCallable implements Callable<JSONObject> {

    private ReturnMoneyDbservice returnMoneyDbservice;
    private UserAccountDbService userAccountDbService;
    private SysCompanyDbService companyDbService;
    private CustomerContractDbService contractDbService;
    private CustomerProductOrderDbService productOrderDbService;
    private CustomerDbService customerDbService;
    private ImportFailureLogDbService importFailureLogDbService;
    private SendRoyaltyDbService sendRoyaltyDbService;
    private List<ImportReturnMoneyVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private String companyId;

    public InsertReturnMoneyCallable(ReturnMoneyDbservice returnMoneyDbservice, List<ImportReturnMoneyVO> list, CountDownLatch begin,
                                     CountDownLatch end, String companyId, UserAccountDbService userAccountDbService,
                                     ImportFailureLogDbService importFailureLogDbService, CustomerDbService customerDbService,
                                     CustomerProductOrderDbService productOrderDbService,SysCompanyDbService companyDbService,
                                     CustomerContractDbService contractDbService,SendRoyaltyDbService sendRoyaltyDbService) {
        this.returnMoneyDbservice = returnMoneyDbservice;
        this.sendRoyaltyDbService = sendRoyaltyDbService;
        this.userAccountDbService = userAccountDbService;
        this.productOrderDbService = productOrderDbService;
        this.customerDbService = customerDbService;
        this.companyDbService = companyDbService;
        this.contractDbService = contractDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.companyId = companyId;
    }

    @SneakyThrows
    @Override
    public JSONObject call() {
        UserAccount loginUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息

        //导入数量
        int importNum = 0;
        //重复的行数
        //String repeatIdStr = "";
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        //String importFailIdStr = "";
        List<Integer> importFailIdStr = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        for (int i=0;i<list.size();i++) {
            boolean b = true;
            String reasonForFailure =null;
            ReturnMoney returnMoney =new ReturnMoney();
            ImportReturnMoneyVO importVO = list.get(i);
            List<ImportFailureLogVO> logVOList = importFailureLogDbService.selectImportFailureLogByNameAndType(importVO.getArriveNum(),8,companyId,null);
            if (logVOList.size() > 0){
                for (int k=0;k<logVOList.size();k++){
                    if (logVOList.get(k).getImportData().equals(JSONObject.toJSONString(importVO))){
                        if (logVOList.get(k).getLogType().equals("1")){
                            //重复
                            repeatIdStr.add(i+2);
                        }else if (logVOList.get(k).getLogType().equals("2")){
                            //导入失败
                            importFailIdStr.add(i+2);
                        }
                        b =false;
                        break;
                    }
                }
            }
            if (b){

                ReturnMoneyVO returnMoneyVO =returnMoneyDbservice.selectReturnMoneyByNumber(importVO.getArriveNum());
                if (Objects.isNull(returnMoneyVO) || Objects.isNull(returnMoneyVO.getReturnMoneyId())){
                    returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                    Date arriveTime = null;
                    Date createTm = null;
                    Date royaltyRecordTime = null;
                    if (Objects.nonNull(importVO.getArriveTime())){
                        //同一个Excel有不一样的时间格式……
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        arriveTime= simpleDateFormat.parse(importVO.getArriveTime());
                        returnMoney.setArriveTime(arriveTime);
                    }
                    if (Objects.nonNull(importVO.getCreateTm())){
                        //同一个Excel有不一样的时间格式……
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        int index = importVO.getCreateTm().indexOf(":");
                        if (index != -1 && importVO.getCreateTm().substring(index+1).indexOf(":") != -1){
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        }
                        createTm= simpleDateFormat.parse(importVO.getCreateTm());
                        returnMoney.setCreateTm(createTm);
                    }
                    if (Objects.nonNull(importVO.getArriveMethod())){
                        Integer  arriveMethod = null;
                        if ("银行汇款".equals(importVO.getArriveMethod())){
                            arriveMethod = 0;
                        }
                        if ("现金".equals(importVO.getArriveMethod())){
                            arriveMethod = 1;
                        }
                        if ("微信".equals(importVO.getArriveMethod()) || "支付宝".equals(importVO.getArriveMethod())){
                            arriveMethod = 3;
                        }
                        returnMoney.setArriveMethod(arriveMethod);
                    }
                    returnMoney.setArriveNum(importVO.getArriveNum());
                    returnMoney.setArriveMoney(new BigDecimal(importVO.getArriveMoney()));
                    CustomerVO customerVO = customerDbService.selectCustomerByName(importVO.getCustomerName());
                    if (Objects.isNull(customerVO) || Objects.isNull(customerVO.getCustomerId())){

                        //b = false;
                        //reasonForFailure = "第"+i+2+"行，客户名称："+importVO.getCustomerName()+"客户匹配失败";

                    }else {
                        returnMoney.setCustomerId(customerVO.getCustomerId());
                    }
                    returnMoney.setRemark(importVO.getRemark());
                    CustomerProductOrderVO orderVO = productOrderDbService.selectOrderByNumber(importVO.getOrderNumber());
                    if (Objects.isNull(orderVO) || Objects.isNull(orderVO.getProductOrderId())){
                        //b= false;
                        //reasonForFailure = "第"+i+2+"行，订单编号："+importVO.getOrderNumber()+"订单编号匹配失败";

                    }else {
                        returnMoney.setOrderId(orderVO.getProductOrderId());
                        returnMoney.setContractId(orderVO.getContractId());
                    }
                    returnMoney.setPaymentAccount(importVO.getPaymentAccount());
                    returnMoney.setPaymentUnit(importVO.getPaymentUnit());
                    SysCompany sysCompany = null;
                    returnMoney.setArriveUnitName(importVO.getArriveUnitName());
                    if ("分公司".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(0);
                        //sysCompany = companyDbService.selectSysCompanyById(companyId);
                    }else if ("北京财税研究院".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(1);
                    }else if ("大成方略网络科技有限公司".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(2);
                    }else if ("北京大成方略财务顾问有限公司".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(3);
                    }else if ("北京大成方略纳税人俱乐部有限公司".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(4);
                    }else if ("大成方略纳税人俱乐部股份有限公司".equals(importVO.getArriveUnitName())){
                        returnMoney.setArriveAccountType(5);
                    }
                    /*if (Objects.isNull(sysCompany)){
                        sysCompany = new SysCompany();
                        sysCompany.setCompanyId(CommonUtils.getGUID());
                        sysCompany.setCompanyName(importVO.getArriveUnitName());
                        sysCompany.setCompanyType(1);
                        sysCompany.setCreatePeopleId(loginUserAccount.getAccountId());
                        sysCompany.setCreateTm(new Date());
                        companyDbService.insertCompany(sysCompany);
                    }
                    if (Objects.nonNull(sysCompany)){
                        returnMoney.setArriveUnitName(sysCompany.getCompanyId());
                    }*/
                    if ("已发放".equals(importVO.getRoyaltyStatus())){
                        returnMoney.setRoyaltyStatus(1);
                    }else {
                        returnMoney.setRoyaltyStatus(3);
                    }
                    returnMoney.setRoyaltyMoney(new BigDecimal(importVO.getArriveMoney()));
                    if (Objects.nonNull(importVO.getRoyaltyRecordTime())){
                        //同一个Excel有不一样的时间格式……
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        int index = importVO.getCreateTm().indexOf(":");
                        if (index != -1 && importVO.getCreateTm().substring(index+1).indexOf(":") != -1){
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        }else if (index == -1){
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        royaltyRecordTime= simpleDateFormat.parse(importVO.getRoyaltyRecordTime());
                        returnMoney.setRoyaltyRecordTime(royaltyRecordTime);
                    }
                    UserAccountManagerVO userAccountVO = userAccountDbService.selectUserAccountByNameAndCompanyId(importVO.getSalesmanName(),companyId);
                    if (Objects.nonNull(userAccountVO)){
                        returnMoney.setSalesmanId(userAccountVO.getAccountId());
                    }
                    if ("否".equals(importVO.getArriveIsAbolish())){
                        returnMoney.setArriveIsAbolish(0);
                    }
                    if ("是".equals(importVO.getArriveIsAbolish())){
                        returnMoney.setArriveIsAbolish(1);
                    }
                    returnMoney.setIsBack(0);
                    returnMoney.setIsAbolish(0);
                    returnMoney.setDelFlag(0);
                    returnMoney.setFilialeId(companyId);
                    returnMoney.setSource(importVO.getSource());
                    userAccountVO = userAccountDbService.selectUserAccountByNameAndCompanyId(importVO.getCreateName(),companyId);
                    if (Objects.nonNull(userAccountVO)){
                        returnMoney.setCreateBy(userAccountVO.getAccountId());
                    }
                    returnMoney.setDataSource(1);
                    returnMoney.setUpdateTm(new Date());
                    returnMoney.setUpdateBy(loginUserAccount.getAccountId());
                    if((Objects.isNull(customerVO) || Objects.isNull(customerVO.getCustomerId())) || (Objects.isNull(orderVO) || Objects.isNull(orderVO.getProductOrderId())))  {
                        returnMoney.setMemberErrorData(1);
                    }else {
                        returnMoney.setMemberErrorData(0);
                    }
                    if (b){
                        b = returnMoneyDbservice.addReturnMoney(returnMoney);
                    }
                    if (b){
                        if(returnMoney.getMemberErrorData() == 0) {
                            updateOrderCompleteTm(returnMoney,orderVO);
                            updateContractPaymentTm(returnMoney,orderVO);
                            //提成发放表暂时不写
                            //OrderSendRoyalty orderSendRoyalty = new OrderSendRoyalty();
                            //addSendRoyalty();
                        }
                        importNum = importNum+1;

                    }else {
                        insertImportFailureLog(importVO,2,returnMoney,reasonForFailure);
                        //导入失败
                        importFailIdStr.add(i+2);
                    }
                }else {
                    //insertImportFailureLog(importVO,1,returnMoney,"第"+i+2+"行，回款编号："+importVO.getArriveNum()+"已存在");
                    //重复
                    repeatIdStr.add(i+2);
                }

            }

        }
        jsonObject.put("importNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }

    public void updateContractPaymentTm(ReturnMoney returnMoney,CustomerProductOrderVO orderVO){
        if (Objects.nonNull(orderVO.getContractId())){
            CustomerContract customerContract = contractDbService.selectContractById(orderVO.getContractId());
            if (Objects.nonNull(customerContract) && (Objects.isNull(customerContract.getPaymentDate()) || customerContract.getPaymentDate().getTime() < returnMoney.getArriveTime().getTime())){
                customerContract.setPaymentDate(returnMoney.getArriveTime());
                customerContract.setUpdateTm(new Date());
                contractDbService.updateCustomerContract(customerContract);
            }
        }
    }

    /**
     * 更新订单完成时间
     * @param returnMoney
     * @param orderVO
     */
    public void updateOrderCompleteTm(ReturnMoney returnMoney,CustomerProductOrderVO orderVO){
        if (Objects.isNull(orderVO.getOrderCompleteTm()) || orderVO.getOrderCompleteTm().getTime() < returnMoney.getArriveTime().getTime()){
            CustomerProductOrder customerProductOrder = new CustomerProductOrder();
            customerProductOrder.setProductOrderId(returnMoney.getOrderId());
            customerProductOrder.setOrderCompleteTm(returnMoney.getArriveTime());
            customerProductOrder.setUpdateTm(new Date());
            productOrderDbService.updateProductOrder(customerProductOrder);
        }
    }

    /**
     * 记录导入失败日志
     * @param importVO
     * @param type
     */
    public void insertImportFailureLog(ImportReturnMoneyVO importVO,
                                       Integer type,
                                       ReturnMoney returnMoney,
                                       String reasonForFailure){
        UserAccount logUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        ImportFailureLog importFailureLog = new ImportFailureLog();;
        if (type == 1){
            ReturnMoneyVO returnMoneyVO =returnMoneyDbservice.selectReturnMoneyByNumber(importVO.getArriveNum());
            importFailureLog.setDataId(returnMoneyVO.getReturnMoneyId());
        }
        UserAccountManagerVO accountManagerVO = userAccountDbService.selectUserAccountByNameAndCompanyId(companyId,importVO.getCreateName());
        if (Objects.nonNull(accountManagerVO)){
            importFailureLog.setAccountId(accountManagerVO.getAccountId());
        }
        UserAccountManagerVO userAccountVO = userAccountDbService.selectUserAccountByNameAndCompanyId(importVO.getSalesmanName(),companyId);
        if (Objects.nonNull(userAccountVO)){
            importFailureLog.setAccountId(userAccountVO.getAccountId());
        }
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(logUserAccount.getAccountId());
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType("8");
        importFailureLog.setImportName(importVO.getArriveNum());
        if (null ==reasonForFailure){
            importFailureLog.setReasonForFailure("数据错误");
        }else {
            importFailureLog.setReasonForFailure(reasonForFailure);
        }
        importFailureLog.setImportData(JSONObject.toJSONString(importVO));
        importFailureLog.setLogType(String.valueOf(type));
        importFailureLog.setCompanyId(companyId);
        importFailureLogDbService.insertImportFailureLog(importFailureLog);
    }
}
